/**
 * @author Loganli
 * 导航工具箱 - 常用开发工具集合
 */

// 工具箱管理器
const ToolboxManager = {
    // 当前激活的工具
    activeToolId: null,
    
    // 初始化工具箱
    init() {
        // 绑定工具切换事件
        document.querySelectorAll('.sidebar-tool-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const toolId = item.getAttribute('data-tool-id');
                if (toolId) {
                    this.showTool(toolId);
                    e.preventDefault();
                }
            });
        });
        
        // 绑定工具箱关闭按钮
        document.querySelector('#closeToolbox')?.addEventListener('click', () => {
            this.hideToolbox();
        });
        
        // 绑定工具箱切换按钮
        document.querySelector('#toggleToolbox')?.addEventListener('click', () => {
            const toolbox = document.querySelector('#toolbox');
            if (toolbox.classList.contains('hidden')) {
                if (this.activeToolId) {
                    this.showTool(this.activeToolId);
                } else {
                    this.showTool('ipLookup'); // 默认显示IP查询工具
                }
            } else {
                this.hideToolbox();
            }
        });
    },
    
    // 显示工具箱
    showToolbox() {
        const toolbox = document.querySelector('#toolbox');
        toolbox.classList.remove('hidden');
        document.body.classList.add('toolbox-open');
    },
    
    // 隐藏工具箱
    hideToolbox() {
        const toolbox = document.querySelector('#toolbox');
        toolbox.classList.add('hidden');
        document.body.classList.remove('toolbox-open');
    },
    
    // 显示特定工具
    showTool(toolId) {
        // 隐藏所有工具内容
        document.querySelectorAll('.tool-content').forEach(content => {
            content.classList.add('hidden');
        });
        
        // 取消所有工具项的激活状态
        document.querySelectorAll('.sidebar-tool-item').forEach(item => {
            item.classList.remove('active');
        });
        
        // 显示选中的工具内容
        const toolContent = document.querySelector(`#${toolId}Content`);
        if (toolContent) {
            toolContent.classList.remove('hidden');
            
            // 激活对应的工具项
            const toolItem = document.querySelector(`.sidebar-tool-item[data-tool-id="${toolId}"]`);
            if (toolItem) {
                toolItem.classList.add('active');
            }
            
            // 显示工具箱
            this.showToolbox();
            
            // 更新当前激活的工具ID
            this.activeToolId = toolId;
        }
    }
};

// IP归属地查询工具
const IpLookupTool = {
    init() {
        const form = document.querySelector('#ipLookupForm');
        const result = document.querySelector('#ipLookupResult');
        
        if (form) {
            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                const ipInput = form.querySelector('input[name="ip"]');
                const ip = ipInput.value.trim();
                
                if (!ip) {
                    result.innerHTML = '<div class="text-red-500">请输入IP地址</div>';
                    return;
                }
                
                result.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin"></i> 查询中...</div>';
                
                try {
                    const response = await fetch(`https://ip.useragentinfo.com/json?ip=${ip}`);
                    const data = await response.json();
                    
                    if (data.code === 0) {
                        let html = '<div class="bg-opacity-10 bg-blue-500 p-4 rounded-lg">';
                        html += `<div class="mb-2"><span class="font-semibold">IP：</span>${data.data.ip}</div>`;
                        html += `<div class="mb-2"><span class="font-semibold">国家/地区：</span>${data.data.country || '未知'}</div>`;
                        html += `<div class="mb-2"><span class="font-semibold">省份：</span>${data.data.province || '未知'}</div>`;
                        html += `<div class="mb-2"><span class="font-semibold">城市：</span>${data.data.city || '未知'}</div>`;
                        html += `<div><span class="font-semibold">运营商：</span>${data.data.isp || '未知'}</div>`;
                        html += '</div>';
                        result.innerHTML = html;
                    } else {
                        result.innerHTML = `<div class="text-red-500">查询失败：${data.message}</div>`;
                    }
                } catch (error) {
                    result.innerHTML = `<div class="text-red-500">查询失败：${error.message}</div>`;
                }
            });
        }
    }
};

// 正则表达式测试工具
const RegexTool = {
    init() {
        const form = document.querySelector('#regexForm');
        const result = document.querySelector('#regexResult');
        const patternInput = document.querySelector('#regexPattern');
        const textInput = document.querySelector('#regexText');
        const flagsInput = document.querySelector('#regexFlags');
        
        if (form) {
            const updateResult = () => {
                const pattern = patternInput.value;
                const text = textInput.value;
                const flags = flagsInput.value;
                
                if (!pattern || !text) {
                    result.innerHTML = '';
                    return;
                }
                
                try {
                    const regex = new RegExp(pattern, flags);
                    const matches = [...text.matchAll(regex)];
                    
                    if (matches.length === 0) {
                        result.innerHTML = '<div class="text-yellow-500">没有匹配结果</div>';
                        return;
                    }
                    
                    let html = '<div class="bg-opacity-10 bg-blue-500 p-4 rounded-lg">';
                    html += `<div class="mb-2">共找到 <span class="font-semibold">${matches.length}</span> 个匹配项</div>`;
                    html += '<div class="space-y-2">';
                    
                    matches.forEach((match, index) => {
                        html += `<div class="p-2 bg-opacity-20 bg-blue-500 rounded">`;
                        html += `<div class="font-semibold">匹配 #${index + 1}：</div>`;
                        html += `<div class="font-mono">${match[0]}</div>`;
                        
                        if (match.length > 1) {
                            html += `<div class="mt-1 font-semibold">捕获组：</div>`;
                            for (let i = 1; i < match.length; i++) {
                                html += `<div class="font-mono">组 ${i}: ${match[i]}</div>`;
                            }
                        }
                        
                        html += `<div class="mt-1"><span class="font-semibold">位置：</span>索引 ${match.index}</div>`;
                        html += '</div>';
                    });
                    
                    html += '</div></div>';
                    result.innerHTML = html;
                } catch (error) {
                    result.innerHTML = `<div class="text-red-500">正则表达式错误：${error.message}</div>`;
                }
            };
            
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                updateResult();
            });
            
            // 实时更新结果（可选）
            patternInput.addEventListener('input', updateResult);
            textInput.addEventListener('input', updateResult);
            flagsInput.addEventListener('input', updateResult);
        }
    }
};

// Crontab时间计算工具
const CrontabTool = {
    init() {
        const form = document.querySelector('#crontabForm');
        const result = document.querySelector('#crontabResult');
        
        if (form) {
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                const expression = form.querySelector('input[name="crontab"]').value.trim();
                
                if (!expression) {
                    result.innerHTML = '<div class="text-red-500">请输入Crontab表达式</div>';
                    return;
                }
                
                try {
                    // 简单的crontab解析
                    const parts = expression.split(/\s+/);
                    if (parts.length < 5 || parts.length > 6) {
                        throw new Error('Crontab表达式应该有5-6个字段');
                    }
                    
                    // 这里只是一个简单的示例，实际应用中需要更复杂的解析逻辑
                    const now = new Date();
                    const nextDates = [];
                    
                    // 计算未来5次执行时间（简化版）
                    let currentDate = new Date(now);
                    for (let i = 0; i < 5; i++) {
                        currentDate = this.getNextExecutionTime(currentDate, expression);
                        nextDates.push(new Date(currentDate));
                        currentDate.setMinutes(currentDate.getMinutes() + 1); // 避免重复
                    }
                    
                    let html = '<div class="bg-opacity-10 bg-blue-500 p-4 rounded-lg">';
                    html += '<div class="mb-2 font-semibold">未来5次执行时间：</div>';
                    html += '<div class="space-y-1">';
                    
                    nextDates.forEach((date, index) => {
                        const formattedDate = this.formatDate(date);
                        const relativeTime = this.getRelativeTime(now, date);
                        html += `<div>${index + 1}. ${formattedDate} <span class="text-sm opacity-80">(${relativeTime})</span></div>`;
                    });
                    
                    html += '</div></div>';
                    result.innerHTML = html;
                } catch (error) {
                    result.innerHTML = `<div class="text-red-500">解析错误：${error.message}</div>`;
                }
            });
        }
    },
    
    // 获取下一次执行时间（简化版）
    getNextExecutionTime(currentDate, expression) {
        // 注意：这是一个非常简化的版本，仅用于演示
        // 实际应用中应该使用专门的crontab解析库
        
        // 这里简单地增加一小时作为演示
        const nextDate = new Date(currentDate);
        nextDate.setHours(nextDate.getHours() + 1);
        return nextDate;
    },
    
    // 格式化日期
    formatDate(date) {
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
    },
    
    // 获取相对时间描述
    getRelativeTime(now, future) {
        const diff = future - now;
        const seconds = Math.floor(diff / 1000);
        
        if (seconds < 60) return `${seconds}秒后`;
        
        const minutes = Math.floor(seconds / 60);
        if (minutes < 60) return `${minutes}分钟后`;
        
        const hours = Math.floor(minutes / 60);
        if (hours < 24) return `${hours}小时后`;
        
        const days = Math.floor(hours / 24);
        return `${days}天后`;
    }
};

// SQL格式化工具
const SqlFormatterTool = {
    init() {
        const input = document.querySelector('#sqlInput');
        const output = document.querySelector('#sqlOutput');
        const formatBtn = document.querySelector('#formatSql');
        const minifyBtn = document.querySelector('#minifySql');
        const copyBtn = document.querySelector('#copySql');
        
        if (input && output) {
            formatBtn.addEventListener('click', () => {
                const sql = input.value.trim();
                if (!sql) {
                    output.value = '';
                    return;
                }
                
                try {
                    // 简单的SQL格式化（实际应用中应使用专门的库）
                    const formatted = this.formatSQL(sql);
                    output.value = formatted;
                } catch (error) {
                    output.value = `错误：${error.message}`;
                }
            });
            
            minifyBtn.addEventListener('click', () => {
                const sql = input.value.trim();
                if (!sql) {
                    output.value = '';
                    return;
                }
                
                try {
                    // 简单的SQL压缩
                    const minified = this.minifySQL(sql);
                    output.value = minified;
                } catch (error) {
                    output.value = `错误：${error.message}`;
                }
            });
            
            copyBtn.addEventListener('click', () => {
                if (!output.value) return;
                
                output.select();
                document.execCommand('copy');
                
                const originalText = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i class="fas fa-check"></i> 已复制';
                
                setTimeout(() => {
                    copyBtn.innerHTML = originalText;
                }, 2000);
            });
        }
    },
    
    // 简单的SQL格式化
    formatSQL(sql) {
        // 这是一个非常简化的实现，实际应用中应使用专门的SQL格式化库
        return sql
            .replace(/\s+/g, ' ')
            .replace(/\s*,\s*/g, ', ')
            .replace(/\s*;\s*/g, ';\n')
            .replace(/\s*(\()\s*/g, ' $1')
            .replace(/\s*(\))\s*/g, '$1 ')
            .replace(/\s*(SELECT|FROM|WHERE|GROUP BY|HAVING|ORDER BY|LIMIT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE)\s+/gi, '\n$1 ')
            .replace(/\s*(INNER|LEFT|RIGHT|FULL|OUTER|CROSS)?\s*JOIN\s+/gi, '\n$1 JOIN ')
            .replace(/\s*(ON|AND|OR)\s+/gi, '\n  $1 ');
    },
    
    // 简单的SQL压缩
    minifySQL(sql) {
        return sql
            .replace(/\s+/g, ' ')
            .replace(/\s*,\s*/g, ',')
            .replace(/\s*;\s*/g, ';')
            .replace(/\s*(\()\s*/g, '(')
            .replace(/\s*(\))\s*/g, ')')
            .trim();
    }
};

// JSON工具
const JsonTool = {
    init() {
        const input = document.querySelector('#jsonInput');
        const output = document.querySelector('#jsonOutput');
        const formatBtn = document.querySelector('#formatJson');
        const minifyBtn = document.querySelector('#minifyJson');
        const validateBtn = document.querySelector('#validateJson');
        const copyBtn = document.querySelector('#copyJson');
        
        if (input && output) {
            formatBtn.addEventListener('click', () => {
                const json = input.value.trim();
                if (!json) {
                    output.value = '';
                    return;
                }
                
                try {
                    const obj = JSON.parse(json);
                    output.value = JSON.stringify(obj, null, 2);
                    output.classList.remove('text-red-500');
                } catch (error) {
                    output.value = `错误：${error.message}`;
                    output.classList.add('text-red-500');
                }
            });
            
            minifyBtn.addEventListener('click', () => {
                const json = input.value.trim();
                if (!json) {
                    output.value = '';
                    return;
                }
                
                try {
                    const obj = JSON.parse(json);
                    output.value = JSON.stringify(obj);
                    output.classList.remove('text-red-500');
                } catch (error) {
                    output.value = `错误：${error.message}`;
                    output.classList.add('text-red-500');
                }
            });
            
            validateBtn.addEventListener('click', () => {
                const json = input.value.trim();
                if (!json) {
                    output.value = '';
                    return;
                }
                
                try {
                    JSON.parse(json);
                    output.value = "JSON 格式有效";
                    output.classList.remove('text-red-500');
                } catch (error) {
                    output.value = `JSON 格式无效：${error.message}`;
                    output.classList.add('text-red-500');
                }
            });
            
            copyBtn.addEventListener('click', () => {
                if (!output.value) return;
                
                output.select();
                document.execCommand('copy');
                
                const originalText = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i class="fas fa-check"></i> 已复制';
                
                setTimeout(() => {
                    copyBtn.innerHTML = originalText;
                }, 2000);
            });
        }
    }
};

// 时间戳转换工具
const TimestampTool = {
    init() {
        const nowBtn = document.querySelector('#timestampNow');
        const convertBtn = document.querySelector('#convertTimestamp');
        const timestampInput = document.querySelector('#timestamp');
        const dateInput = document.querySelector('#datetime');
        const result = document.querySelector('#timestampResult');
        
        if (nowBtn && convertBtn) {
            // 获取当前时间戳
            nowBtn.addEventListener('click', () => {
                const now = new Date();
                timestampInput.value = Math.floor(now.getTime() / 1000);
                dateInput.value = this.formatDateForInput(now);
                this.updateResult(now);
            });
            
            // 时间戳转日期
            timestampInput.addEventListener('input', () => {
                const timestamp = parseInt(timestampInput.value.trim());
                if (isNaN(timestamp)) return;
                
                const date = new Date(timestamp * 1000);
                dateInput.value = this.formatDateForInput(date);
                this.updateResult(date);
            });
            
            // 日期转时间戳
            dateInput.addEventListener('input', () => {
                const dateStr = dateInput.value.trim();
                if (!dateStr) return;
                
                const date = new Date(dateStr);
                timestampInput.value = Math.floor(date.getTime() / 1000);
                this.updateResult(date);
            });
            
            // 转换按钮
            convertBtn.addEventListener('click', () => {
                const timestamp = parseInt(timestampInput.value.trim());
                if (!isNaN(timestamp)) {
                    const date = new Date(timestamp * 1000);
                    dateInput.value = this.formatDateForInput(date);
                    this.updateResult(date);
                } else {
                    const dateStr = dateInput.value.trim();
                    if (dateStr) {
                        const date = new Date(dateStr);
                        timestampInput.value = Math.floor(date.getTime() / 1000);
                        this.updateResult(date);
                    }
                }
            });
            
            // 初始化显示当前时间
            const now = new Date();
            timestampInput.value = Math.floor(now.getTime() / 1000);
            dateInput.value = this.formatDateForInput(now);
            this.updateResult(now);
        }
    },
    
    // 更新结果显示
    updateResult(date) {
        const result = document.querySelector('#timestampResult');
        if (!result) return;
        
        const timestamp = Math.floor(date.getTime() / 1000);
        const formattedDate = date.toLocaleString('zh-CN');
        const relativeTime = this.getRelativeTime(new Date(), date);
        
        let html = '<div class="bg-opacity-10 bg-blue-500 p-4 rounded-lg">';
        html += `<div class="mb-2"><span class="font-semibold">Unix时间戳：</span>${timestamp}</span></div>`;
        html += `<div class="mb-2"><span class="font-semibold">日期时间：</span>${formattedDate}</div>`;
        html += `<div><span class="font-semibold">相对时间：</span>${relativeTime}</div>`;
        html += '</div>';
        
        result.innerHTML = html;
    },
    
    // 格式化日期用于input
    formatDateForInput(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        
        return `${year}-${month}-${day}T${hours}:${minutes}`;
    },
    
    // 获取相对时间描述
    getRelativeTime(now, target) {
        const diff = target - now;
        const absDiff = Math.abs(diff);
        const seconds = Math.floor(absDiff / 1000);
        const isPast = diff < 0;
        const suffix = isPast ? '前' : '后';
        
        if (seconds < 60) return `${seconds}秒${suffix}`;
        
        const minutes = Math.floor(seconds / 60);
        if (minutes < 60) return `${minutes}分钟${suffix}`;
        
        const hours = Math.floor(minutes / 60);
        if (hours < 24) return `${hours}小时${suffix}`;
        
        const days = Math.floor(hours / 24);
        if (days < 30) return `${days}天${suffix}`;
        
        const months = Math.floor(days / 30);
        if (months < 12) return `${months}个月${suffix}`;
        
        const years = Math.floor(months / 12);
        return `${years}年${suffix}`;
    }
};

// 初始化所有工具
document.addEventListener('DOMContentLoaded', () => {
    ToolboxManager.init();
    IpLookupTool.init();
    RegexTool.init();
    CrontabTool.init();
    SqlFormatterTool.init();
    JsonTool.init();
    TimestampTool.init();
});
